package com.example.provider.log.processor;

import com.example.api.common.entity.OperationLog;
import com.example.api.common.log.LogEvent;
import com.example.api.common.log.LogProcessor;
import com.example.api.common.log.LogStorage;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class StructuredLogProcessor implements LogProcessor {
    @Autowired
    private LogStorage logStorage;
    
    private static final ObjectMapper objectMapper = new ObjectMapper();
    
    @Override
    public void process(LogEvent event) {
        try {
            OperationLog log = convertToOperationLog(event);
            logStorage.store(log);
        } catch (Exception e) {
            log.error("Failed to process log event", e);
        }
    }
    
    private OperationLog convertToOperationLog(LogEvent event) {
        OperationLog log = new OperationLog();
        log.setTraceId(event.getTraceId());
        log.setApplicationName(event.getServiceName());
        log.setClassName(event.getClassName());
        log.setMethodName(event.getMethodName());
        log.setRequestParams(convertToString(event.getRequest()));
        log.setResponseResult(convertToString(event.getResponse()));
        log.setExecutionTime(event.getExecutionTime());
        log.setStatus(event.getThrowable() != null ? 1 : 0);
        log.setErrorMessage(event.getThrowable() != null ? event.getThrowable().getMessage() : null);
        log.setOperationTime(event.getTimestamp());
        return log;
    }
    
    private String convertToString(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            log.error("Failed to convert object to string", e);
            return null;
        }
    }
} 